package com.qq2008.game.mojie.controller;


import com.qq2008.game.mojie.entity.Message;
import com.qq2008.game.mojie.form.JSONResult;
import com.qq2008.game.mojie.jdo.User;
import com.qq2008.game.mojie.utils.CommonUtil;
import com.qq2008.game.mojie.annotation.AuthPassport;
import com.qq2008.game.mojie.jdo.*;
import com.qq2008.game.mojie.server.*;
import com.qq2008.game.mojie.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/mojie")
// 魔界")
public class MoController {

    @Resource
    private RoleService roleService;


    /**
     * game
     */
    @RequestMapping(value = {"/game"})
    @AuthPassport
    public String game(String cmd) {
        System.out.println(cmd);
        if (null == cmd || StringUtils.isEmpty(cmd)) {
            cmd = "scene";
        }
        return "forward:/mojie/" + cmd;
    }

    /**
     * 选区
     */
    @GetMapping(value = {"", "/", "/server"})
    public String server(Model model) {
        model.addAttribute("pageTitle", "服务器");
        return "server";
    }

    /**
     * 选择角色
     */
    @GetMapping(value = "/main")
    public String main(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", user.getUserID());
        List<Role> roleList = roleService.list(params);
        model.addAttribute("roleList", roleList);
        model.addAttribute("pageTitle", "选择角色");
        return "main";
    }

    /**
     * 场景
     */
    @GetMapping(value = "/scene")
    public String scene(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        Room room = SceneServer.getRoom(role.getRoomId());
        model.addAttribute("room", room);
        model.addAttribute("timeDesc", "初春的深夜，月亮在云中忽隐忽现，四周漆黑一片");
        model.addAttribute("pageTitle", "魔界");
        return "scene";
    }

    private Role getSessionRole(HttpSession session) {
        return RoleServer.getRole((int) session.getAttribute("roleId"));
    }

    /**
     * 走向北
     */
    @GetMapping(value = "/north")
    public String north(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        if (null != role) {
            int mapId = role.getRoomId();
            Room room = SceneServer.getRoom(mapId);
            if (null != room && null != room.getNorth()) {
                role.setRoomId(room.getNorth().getId());
            }
        }

        model.addAttribute("pageTitle", "魔界");
        return "redirect:game?cmd=scene";
    }

    /**
     * 走向东
     */
    @GetMapping(value = "/east")
    public String east(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        if (null != role) {
            int mapId = role.getRoomId();
            Room room = SceneServer.getRoom(mapId);
            if (null != room && null != room.getEast()) {
                role.setRoomId(room.getEast().getId());
            }
        }

        model.addAttribute("pageTitle", "魔界");
        return "redirect:game?cmd=scene";
    }

    /**
     * 走向南
     */
    @GetMapping(value = "/south")
    public String south(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        if (null != role) {
            int mapId = role.getRoomId();
            Room room = SceneServer.getRoom(mapId);
            if (null != room && null != room.getSouth()) {
                role.setRoomId(room.getSouth().getId());
            }

        }

        model.addAttribute("pageTitle", "魔界");
        return "redirect:game?cmd=scene";
    }

    /**
     * 走向西
     */
    @GetMapping(value = "/west")
    public String west(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        if (null != role) {
            int mapId = role.getRoomId();
            Room room = SceneServer.getRoom(mapId);
            if (null != room && null != room.getWest()) {
                role.setRoomId(room.getWest().getId());
            }
        }

        model.addAttribute("pageTitle", "魔界");
        return "redirect:game?cmd=scene";
    }


    /**
     * 传送
     */
    @GetMapping(value = "/trans")
    public String trans(Model model, HttpSession session, int roomId) {
        Role role = getSessionRole(session);
        if (null != role) {
            Room room = SceneServer.getRoom(roomId);
            if (null != room) {
                role.setRoomId(roomId);
            }
        }

        model.addAttribute("pageTitle", "魔界");
        return "redirect:game?cmd=scene";
    }


    /**
     * 获取怪物信息
     */
    @GetMapping(value = "/monster")
    public String monster(Model model, int mid, HttpSession session) {
        Role role = getSessionRole(session);
        Monster monster = NpcServer.getNpc(mid);

        // 怪物信息检测
        if (null == monster) {
            Message message = new Message("怪物不存在", "返回游戏", "game?cmd=scene");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        // 不在怪物所在地图
        if (role.getRoomId() != monster.getRoomId()) {
            Message message = new Message("怪物不存在", "返回游戏", "game?cmd=scene");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        model.addAttribute("monster", monster);

        model.addAttribute("pageTitle", "魔界");
        return "monster";
    }

    /**
     * 获取怪物信息
     */
    @GetMapping(value = "/monsterTalk")
    public String monsterTalk(Model model, int mid) {
        Monster monster = NpcServer.getNpc(mid);
        if (null == monster) {

            Message message = new Message("怪物不存在", "返回游戏", "game?cmd=scene");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        model.addAttribute("monster", monster);

        model.addAttribute("pageTitle", "魔界");
        return "monster_talk";
    }

    /**
     * 获取玩家信息
     */
    @GetMapping(value = "/info")
    public String info(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        model.addAttribute("role", role);

        model.addAttribute("pageTitle", "玩家信息");
        return "info";
    }

    /**
     * 获取玩家信息
     */
    @GetMapping(value = "/info2")
    public String info2(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        model.addAttribute("role", role);

        model.addAttribute("pageTitle", "玩家信息");
        return "info2";
    }

    /**
     * 发起战斗PVE
     */
    @GetMapping(value = "/battle")
    public String battle(Model model, int mid, HttpSession session) {
        Monster npc = NpcServer.getNpc(mid);
        Role role = getSessionRole(session);
        // 怪物信息检测
        if (null == npc || npc.getDead()) {
            Message message = new Message("怪物不存在", "返回游戏", "game?cmd=scene");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        // 不在怪物所在地图
        if (role.getRoomId() != npc.getRoomId()) {
            return "redirect:game?cmd=main";
        }
        // 死亡状态检测
        if (role.getDead()) {
            Message message = new Message("你已经死亡", "返回游戏", "game?cmd=scene");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        // 战斗状态检测
        if (null != role.getBattle() && !role.getBattle().isOver()) {
            Message message = new Message("你正在战斗中", "返回游戏", "redirect:showBattle");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        if (null != npc.getBattle() && !npc.getBattle().isOver()) {
            Message message = new Message("怪物正在战斗中", "返回游戏", "redirect:showBattle");
            model.addAttribute("message", message);
            return message.getTemplateUrl();
        }
        // 初始化战斗
        Room room = SceneServer.getRoom(npc.getRoomId());
        Battle battle = new Battle(room, BattleType.PVE, role, npc);
        Thread th = new Thread(battle);
        th.start();

        // 更新状态
        npc.setBattle(battle);
        role.setBattle(battle);

        // 战斗信息
        model.addAttribute("npc", npc);
        model.addAttribute("role", role);
        List<String> msg = battle.getBattleList();
        model.addAttribute("msg", msg);

        model.addAttribute("pageTitle", "魔界");
        return "battle";
    }

    /**
     * 战斗
     */
    @GetMapping(value = "/showBattle")
    public String showBattle(Model model, HttpSession session, RedirectAttributes attr) {
        Role role = getSessionRole(session);
        if (null != role && null != role.getBattle()) {
            Battle battle = role.getBattle();
            // 战斗信息
            List<String> battleMessageList = battle.getBattleList();
            model.addAttribute("battleMessageList", battleMessageList);
            // 属性信息
            Role moRole = (Role) battle.getAttacker();
            Monster moMonster = (Monster) battle.getDefender();
            model.addAttribute("npc", moMonster);
            model.addAttribute("role", moRole);

            // 模板选择
            if (battle.isOver()) {
                attr.addFlashAttribute("battleMessageList", battleMessageList);
                role.setBattle(null);
                model.addAttribute("pageTitle", "战斗结束");
                return "redirect:game?cmd=scene";
            } else {
                model.addAttribute("pageTitle", "战斗中");
                return "battle";
            }
        } else {
            return "redirect:game?cmd=scene";
        }
    }

    /**
     * 战斗结果
     */
    @GetMapping(value = "/battleResult")
    public String battleResult(Model model) {
        model.addAttribute("pageTitle", "魔界");
        return "battle_result";
    }

    /**
     * 战斗逃跑
     */
    @GetMapping(value = "/battleFlee")
    public String battleFlee(Model model, HttpSession session) {
        System.out.println(0);
        Role role = getSessionRole(session);
        if (null != role && null != role.getBattle()) {
            Battle battle = role.getBattle();
            if (null == battle) {
                return "redirect:game?cmd=scene";
            }
            System.out.println(1);
            Role moRole = (Role) battle.getAttacker();
            Monster moMonster = (Monster) battle.getDefender();
            moRole.setBattle(null);
            moMonster.setBattle(null);
            battle.setOver(true);
            //
            System.out.println(2);
            List<String> msg = battle.getBattleList();
            msg.add(moRole.getName() + "产生了怯意!");
            msg.add(moRole.getName() + "逃跑了!");
            msg.add(moRole.getName() + "脱了了战斗!");
            msg.add(moMonster.getName() + "脱了了战斗!");
            model.addAttribute("msg", msg);

            return "battle_result";
        } else {
            return "redirect:game?cmd=scene";
        }
    }

    /**
     * 背包道具列表
     */
    @GetMapping(value = "/bag")
    public String bag(Model model) {

        model.addAttribute("pageTitle", "背包");
        return "bag";
    }

    /**
     * 背包道具详细
     */
    @GetMapping(value = "/bagItem")
    public String bagItem(Model model) {

        model.addAttribute("pageTitle", "背包");
        return "bag_item";
    }

    /**
     * 武器背包
     */
    @GetMapping(value = "/bagWeapon")
    public String bagWeapon(Model model) {

        model.addAttribute("pageTitle", "背包");
        return "bag_weapon";
    }

    /**
     * 技能列表
     */
    @GetMapping(value = "/skill")
    public String skill(Model model) {

        model.addAttribute("pageTitle", "技能");
        return "skill";
    }

    /**
     * 技能详细
     */
    @GetMapping(value = "/skillDetail")
    public String skillDetail(Model model) {
        model.addAttribute("pageTitle", "技能");
        return "skill_detail";
    }

    /**
     * 技能遗忘
     */
    @GetMapping(value = "/skillForget")
    public String skillForget(Model model) {

        model.addAttribute("pageTitle", "技能");
        return "skill";
    }

    /**
     * 技能学习
     */
    @GetMapping(value = "/skillStudy")
    public String skillStudy(Model model) {
        model.addAttribute("pageTitle", "技能");
        return "skill";
    }

    /**
     * 设置默认技能
     */
    @GetMapping(value = "/skillDefault")
    public String skillDefault(Model model) {

        model.addAttribute("pageTitle", "技能");
        return "skill";
    }

    /**
     * 使用技能
     */
    @GetMapping(value = "/skillUse")
    public String skillUse(Model model) {

        model.addAttribute("pageTitle", "技能");
        return "skill";
    }

    /**
     * 传送技能
     */
    @GetMapping(value = "/skillTrans")
    public String skillTrans(Model model) {
        model.addAttribute("pageTitle", "技能");
        return "skill_trans";
    }

    /**
     * 任务列表
     */
    @GetMapping(value = "/task")
    public String task(Model model) {

        model.addAttribute("pageTitle", "任务");
        return "task";
    }

    /**
     * 任务详细
     */
    @GetMapping(value = "/taskDetail")
    public String taskDetail(Model model) {

        model.addAttribute("pageTitle", "任务");
        return "task_detail";
    }

    /**
     * 任务领取
     */
    @GetMapping(value = "/taskReceive")
    public String taskReceive(Model model) {

        model.addAttribute("pageTitle", "任务");
        return "task";
    }

    /**
     * 任务取消
     */
    @GetMapping(value = "/taskCancel")
    public String taskCancel(Model model) {

        model.addAttribute("pageTitle", "任务");
        return "task";
    }

    /**
     * 任务完成
     */
    @GetMapping(value = "/taskAward")
    public String taskAward(Model model) {

        model.addAttribute("pageTitle", "任务");
        return "task";
    }

    /**
     * 复活
     */
    @GetMapping(value = "/roleRelive")
    public String roleRelive(Model model, HttpSession session) {
        Role role = getSessionRole(session);
        // todo 死亡 消耗 场景 副本判断
        EventServer.roleRelive(role);
//        Message message = new Message("救援", "当前场景:教堂!<br />恍惚间, 你看到有人把你背了起来!<br />你得到了救援!", "睁眼", "game?cmd=scene");
        Message message = new Message("救援", "恍惚间, 你看到有人把你背了起来!", "睁眼", "game?cmd=scene");
        model.addAttribute("message", message);
        return message.getTemplateUrl();
    }

    /**
     * 创建角色
     */
    @GetMapping(value = "/createRole")
    public String createRole() {
        return "create_role";
    }

    /**
     * 创建角色
     */
    @PostMapping(value = "/createRole")
    public String createRolePost(Model model, HttpSession session, @ModelAttribute(value = "role") Role role) {
//        System.out.println(JSON.toJSONString(role));
        // TODO 用户名校验
        Map<String, Object> params = new HashMap<>();
        params.put("name", role.getName());
        List<Role> list = roleService.list(params);
//        System.out.println(JSON.toJSONString(list));
        if (!list.isEmpty()) {
            JSONResult result = JSONResult.jsonResult(1, false, "", "角色名已存在", null, null);
            model.addAttribute("error", result);
            return "create_role";
        }
        User user = (User) session.getAttribute("user");
        initRole(role);
        role.setUserId(user.getUserID());

        roleService.insert(role);
//        RoleServer.saveRole(role);
        return "redirect:game?cmd=main";

    }


    /**
     * 登录角色
     */
    @GetMapping(value = "/login")
    public String login(HttpSession session, int roleId) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", user.getUserID());
        params.put("id", roleId);
        List<Role> list = roleService.list(params);
        Role role = list.get(0);
        role.setMaxExp(CommonUtil.calcUpExp(role.getLevel()));
        session.setAttribute("roleId", role.getId());
        RoleServer.saveRole(role);
        if (list.isEmpty()) {
            return "redirect:game?cmd=main";
        }
        return "redirect:game?cmd=scene";
    }


    /**
     * 初始化玩家数据
     */
    private void initRole(Role role) {
        role.setLevel(1);
        role.setHp(10000);
        role.setMaxHP(10000);
        role.setMp(460);
        role.setMaxMP(640);
        role.setMinAttack(20);
        role.setMaxAttack(60);
        role.setMinDefence(32);
        role.setMaxDefence(64);
        role.setSpeed(300);
        role.setRoomId(100);
    }

}
